using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using CKY.AgentPlatform.ModelConfigs.Dto;

namespace CKY.AgentPlatform.ModelConfigs
{
    /// <summary>
    /// 模型配置管理应用服务
    /// </summary>
    public class ModelConfigAppService : ApplicationService, IModelConfigAppService
    {
        private readonly IRepository<ModelConfigs.ModelConfig, Guid> _modelConfigRepository;

        public ModelConfigAppService(IRepository<ModelConfigs.ModelConfig, Guid> modelConfigRepository)
        {
            _modelConfigRepository = modelConfigRepository;
        }

        /// <summary>
        /// 将 ModelConfig 实体转换为 DTO
        /// </summary>
        private ModelConfigDto MapToDto(ModelConfigs.ModelConfig modelConfig)
        {
            return new ModelConfigDto
            {
                Id = modelConfig.Id,
                Name = modelConfig.Name,
                Provider = modelConfig.Provider.ToString(),
                Model = modelConfig.Model,
                Description = modelConfig.Description,
                ApiKey = modelConfig.ApiKey,
                ApiBase = modelConfig.ApiBaseUrl,
                MaxTokens = modelConfig.MaxTokens,
                Temperature = modelConfig.Temperature,
                IsActive = modelConfig.IsActive,
                Status = modelConfig.IsActive ? "Active" : "Inactive",
                CreationTime = modelConfig.CreationTime,
                LastModificationTime = modelConfig.LastModificationTime
            };
        }

        /// <summary>
        /// 获取模型配置分页列表
        /// </summary>
        /// <param name="input">查询参数</param>
        /// <returns>分页结果</returns>
        public async Task<PagedResultDto<ModelConfigDto>> GetListAsync(GetModelConfigListInput input)
        {
            var query = await _modelConfigRepository.GetQueryableAsync();

            // 应用过滤条件
            if (!string.IsNullOrWhiteSpace(input.Filter))
            {
                query = query.Where(m => m.Name.Contains(input.Filter) ||
                                       m.Description.Contains(input.Filter) ||
                                       m.Model.Contains(input.Filter));
            }

            // 获取总数
            var totalCount = await AsyncExecuter.CountAsync(query);

            // 分页查询
            var modelConfigs = await AsyncExecuter.ToListAsync(
                query.PageBy(input.SkipCount, input.MaxResultCount)
            );

            // 转换为DTO
            var modelConfigDtos = modelConfigs.Select(MapToDto).ToList();

            return new PagedResultDto<ModelConfigDto>(totalCount, modelConfigDtos);
        }

        /// <summary>
        /// 根据ID获取模型配置
        /// </summary>
        /// <param name="id">模型配置ID</param>
        /// <returns>模型配置详细信息</returns>
        public async Task<ModelConfigDto> GetAsync(Guid id)
        {
            var modelConfig = await _modelConfigRepository.GetAsync(id);
            return MapToDto(modelConfig);
        }

        /// <summary>
        /// 创建新的模型配置
        /// </summary>
        /// <param name="input">创建参数</param>
        /// <returns>创建的模型配置</returns>
        public async Task<ModelConfigDto> CreateAsync(CreateModelConfigInput input)
        {
            var provider = Enum.Parse<ModelConfigs.ModelProvider>(input.Provider, true);
            var modelConfig = new ModelConfigs.ModelConfig(
                GuidGenerator.Create(),
                input.Name,
                input.Description,
                provider,
                input.Model,
                input.ApiKey);

            await _modelConfigRepository.InsertAsync(modelConfig);
            return MapToDto(modelConfig);
        }

        /// <summary>
        /// 更新模型配置
        /// </summary>
        /// <param name="id">模型配置ID</param>
        /// <param name="input">更新参数</param>
        /// <returns>更新后的模型配置</returns>
        public async Task<ModelConfigDto> UpdateAsync(Guid id, UpdateModelConfigInput input)
        {
            var modelConfig = await _modelConfigRepository.GetAsync(id);

            modelConfig.Name = input.Name ?? modelConfig.Name;
            modelConfig.Description = input.Description ?? modelConfig.Description;
            modelConfig.Model = input.Model ?? modelConfig.Model;
            modelConfig.ApiKey = input.ApiKey ?? modelConfig.ApiKey;
            modelConfig.ApiBaseUrl = input.ApiBase ?? modelConfig.ApiBaseUrl;

            await _modelConfigRepository.UpdateAsync(modelConfig);
            return MapToDto(modelConfig);
        }

        /// <summary>
        /// 删除模型配置
        /// </summary>
        /// <param name="id">模型配置ID</param>
        public async Task DeleteAsync(Guid id)
        {
            await _modelConfigRepository.DeleteAsync(id);
        }

        /// <summary>
        /// 测试模型配置连接
        /// </summary>
        /// <param name="input">测试输入</param>
        /// <returns>测试结果</returns>
        public async Task<TestModelConfigResultDto> TestAsync(TestModelConfigInput input)
        {
            // 简化的测试逻辑
            return new TestModelConfigResultDto
            {
                Success = true,
                Message = "测试成功",
                ResponseTimeMs = 100,
                TestTime = DateTime.UtcNow
            };
        }

        /// <summary>
        /// 批量更新模型配置状态
        /// </summary>
        /// <param name="input">批量更新参数</param>
        public async Task BatchUpdateStatusAsync(BatchUpdateModelConfigStatusInput input)
        {
            foreach (var modelConfigId in input.ModelConfigIds)
            {
                var modelConfig = await _modelConfigRepository.GetAsync(modelConfigId);
                if (input.IsActive)
                {
                    modelConfig.Activate();
                }
                else
                {
                    modelConfig.Deactivate();
                }
                await _modelConfigRepository.UpdateAsync(modelConfig);
            }
        }
    }
}